<template>
  <div v-if="showAll">
    <el-select
      ref="selectTree"
      style="width: 100%"
      v-model="finalName"
      v-bind="$attrs"
      :multiple="multiple"
      :disabled="disabled"
      :clearable="clearable"
      @clear="clearHandle"
      @remove-tag="removeTagHandle"
      :placeholder="placeholder"
    >
      <el-option value="" label="" class="ide-tree-select__options">

        <!-- 树形-动态树 -->
        <el-tree
          class="dynamic-tree"
          :expand-on-click-node="false"
          ref="treeSelect"
          :props="entityProps"
          :load="loadNode"
          lazy
          :show-checkbox="multiple"
          :node-key="valueField"
          :check-strictly="true"
          :highlight-current="true"
          :default-checked-keys="checkedKeys"
          :default-expanded-keys="expandedKeys"
          @node-click="handleNodeClick"
          @check="handleCheck"
          @node-expand="handleNodeExpand"
        >
          <template slot-scope="{ node, data }">
            <span>
              {{ data[labelField] }}
            </span>
          </template>
        </el-tree>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { concat, cloneDeep } from "lodash";
import { AjaxUtil } from "base/lib";
import { findComponentUpward } from '@/utils/util.js'

export default {
  name: "treeselect",
  components: {  },
  props: {
    value: {
      default: null,
    },
    placeholder: {
      default: '',
    },
    settings: {
      type: Object,
      default: () => {},
    },
    entityModel: {
      type: Object,
      default: null,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    finalDisabled: {
      type: false,
    },
    // 回显勾选
    checkedKeys: {
      type: Array,
      default: () => []
    },
    isLoadTable: {
      type: Boolean,
      default: false
    },
    valueField: {
      type: String,
      default: 'value'
    },
    labelField: {
      type: String,
      default: 'label'
    },
    // 允许勾选节点类型
    checkNodeType: {
      type: String,
      default: ''
    }
  },
  computed: {
    // 接口请求
    dispatchProxy() {
      if (Vue.prototype.dispatchProxy) return Vue.prototype.dispatchProxy(this);
      return this.dispatch;
    },
    // 是否展示为树型
    isTreeMode() {
      return true;
    },
    
    
  },
  data() {
    return {
      // 动态树配置
      entityProps: {
        label: this.labelField,
        children: "children",
        isLeaf: "leaf",
      },
      finalName: null, // 展示勾选字段
      finalName_copy: null, // 多选时对比删除tag
      expandedKeys: [], // 默认展开的节点
      showAll: true,
      separate: '@@',
      itemSeparate: '&&',
    };
  },
  watch: {
    // 数据回显
    value: {
      immediate: true,
      handler(val) {
        console.log(val,'===val')
        if (val) {
          const arr = val.split(this.itemSeparate)
          if (arr.length) {
            const finalName = arr.map(s => s.split(this.separate)[1])
            this.checkedKeys = arr.map(s => s.split(this.separate)[0])
            if (this.multiple) {
              this.finalName = finalName
            } else {
              this.finalName = finalName[0]
            }
          } 
        }
      }
    }
  },
  mounted() {
    if (this.multiple) {
      this.$nextTick(() => {
        const { $refs } = findComponentUpward(this)
        $refs?.pmForm?.clearValidate()
      })
    }
  },
  methods: {
    // 静态数据扁平化
    treeToArr(data, res = []) {
      data.forEach((v) => {
        res.push({ ...v });
        let jsonChild = v['children']
        if (jsonChild && jsonChild.length) {
          this.treeToArr(jsonChild, res);
        }
      });
      return res;
    },
    getPlaceholder() {
      if (!this.finalName) return "";
      if (this.multiple) return this.finalName.join(",");
      return this.finalName;
    },
    // 树形-动态树
    async loadNode(node, resolve) {
      // query, leaf,entityName
      if (this.isLoadTable) {
        let {query, leaf, entityName} = await this.$listeners.clickNode(node.data, node) || {}
        if (entityName) {
          let { data } = await AjaxUtil.ajax({
            url: `/api/lowcode/models/actions/query-with-page?entityName=${entityName}&pageIndex=0&pageSize=9999&cascadeDeep=-1`,
            method: 'POST',
            data: query || {}
          })
          console.log(data,'===data')
          let nodes = data.data.map(d => {
            return {
              ...d,
              leaf: leaf
            }
          })
          resolve(nodes)
          console.log(nodes,'===nodes')
        } else {
          resolve([])
        }
      } else {
        let nodes = await this.$listeners.clickNode(node.data, node)
        nodes = nodes.map(n => {
          return {
            ...n,
            disabled: !this.checkNodeType || (n.type !== this.checkNodeType)
          }
        })
        resolve(nodes)
      }
      // this.setCheckedKeys()
    },
    setCheckedKeys(check = true, tempArr) {
      // 勾选已加载的数据
      const arr = this.value && this.value.split(this.itemSeparate) || []
      let valArr = arr.map(a => a.split(this.separate)[0])
      this.$nextTick(() => {
        // if (check) {
          if (this.multiple) {
            this.$refs.treeSelect.setCheckedKeys(valArr)
          } else {
            this.$refs.treeSelect.setCurrentKey(valArr[0])
          }
        // } else {
        //   // 取消选中
        //   if (this.multiple) {
        //     console.log(tempArr,'==tempArr')
        //     this.$refs.treeSelect.setChecked(tempArr, false)
        //   } else {
        //     this.$refs.treeSelect.setCurrentKey(null)
        //   }
        // }
      })
    },
    clearHandle() {
      if (this.multiple) {
        this.$refs.treeSelect.setCheckedKeys([])
      } else {
        this.$refs.treeSelect.setCurrentKey(null)
      }
      this.$emit("input", null);
      this.$emit("selectTreeChange", null);
    },
    // 删除对应值
    removeTagHandle(val) {
      console.log(val,'====removeTagHandle')
      const arr = this.value.split(this.itemSeparate)
      // 优化一下label过滤 TODO
      const result = arr.filter((item) => item.split(this.separate)[1] !== val)
      // 优化一下取消勾选的数据
      // let valArr = arr.filter((item) => item.split(this.separate)[1] === val)
      // valArr = valArr.map(v => v.split(this.separate)[0])
      // console.log(result,'===result')
      // this.$refs.treeSelect.setCheckedKeys(result, true)
      this.$emit('input', result.join(this.itemSeparate))
    },
    handleNodeClick(data) {
      if (!this.multiple && (data.type === this.checkNodeType || !this.checkNodeType)) {
        this.finalName = data[`${this.labelField}`]
        const val = data[`${this.valueField}`] + this.separate + data[this.labelField]
        this.$emit('input', val);
        this.$emit('selectTreeChange', data);
      }
    },
    handleCheck(node, data) {
      let selectData = [];
      data.checkedNodes.forEach(item => {
        // 判断是否设置了allowSelect
        if ((item.type === this.checkNodeType) || !this.checkNodeType) {
          selectData.push(item);
        }
      });
      const value = selectData.map((item) => item[this.valueField] + this.separate + item[this.labelField]);
      this.finalName = selectData.map((s) => s[`${this.labelField}`]);
      this.$emit("input", value.join(this.itemSeparate));
      this.$emit("selectTreeChange", selectData);
    },
    // 默认展开节点数组更新
    handleNodeExpand() {
      this.expandedKeys = []
    },
  },
};
</script>

<style lang="scss" scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: 100%;
  padding: 5px;
  overflow: hidden;
  overflow-y: auto;
}
.ide-tree-select__options.el-select-dropdown__item.selected {
  font-weight: normal;
}
ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}
::v-deep .ide-tree-select__tree .el-tree-node.is-current {
  color: #409eff;
  font-weight: 700;
}
.el-select {
  ::v-deep .el-icon-arrow-up {
    display: block !important;
  }
}
.el-select:hover {
  ::v-deep .el-icon-arrow-up {
    display: none !important;
  }
}
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background-color: #ffffff;
}
::v-deep .el-cascader .el-input .el-input__inner{
  &::placeholder{
     color:#606266;
  }
}
</style>
